package com.trade.module.base.service.impl;

import com.trade.module.base.entity.*;
import com.trade.module.base.repository.*;
import com.trade.module.base.service.UserService;
import com.trade.common.utils.*;
import com.trade.common.utils.crypto.MD5Util;
import com.trade.module.base.vo.UserVo;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Class Description:用户操作服务层实现类
 *
 * @Version v1.0 2017/4/22 0:11
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    /**
     * Field description ：注入用户数据库操作层接口类
     */
    @Autowired
    private UserRepository userRepository;


    /**
     * Field description ：注入用户角色数据库操作层接口类
     */
    @Autowired
    private UserRoleRepository userRoleRepository;

    /**
     * Field description ：注入角色数据库操作层接口类
     */
    @Autowired
    private RoleRepository roleRepository;

    /**
     * Field description ：注入系统日志数据库操作层接口类
     */
    @Autowired
    private SystemLogRepository systemLogRepository;

    /**
     * Field description ：注入部门数据库操作层接口类
     */
    @Autowired
    private DepartmentRepository deptRepostory;

    /**
     * 根据用户名和用户状态查询用户信息
     *
     * @param account  用户名
     * @param userFlag 用户状态
     * @param dataFlag 数据状态
     * @return User 用户信息
     */
    @Override
    public User findByAccountAndUserFlagAndDataFlag(String account, String userFlag, String dataFlag) {
        if (XaUtil.isEmpty(account)) {
            return null;
        }
        return userRepository.findByAccountAndUserFlagAndDataFlag(account, userFlag, dataFlag);
    }

    /**
     * 新增用户
     *
     * @param userVo 用户对象
     * @return user对象
     */
    @Override
    @Transactional
    public User save(UserVo userVo) {
        if (XaUtil.isNotEmpty(userVo)) {
            SearchFilter searchFilter = new SearchFilter("account", SearchFilter.Operator.EQ, userVo.getAccount());
            List<SearchFilter> searchFilterList = new ArrayList<>();
            searchFilterList.add(searchFilter);
            User userTemp = userRepository.findOne(DynamicSpecifications.bySearchFilter(searchFilterList, User.class));
            //根据帐号查询用户，如果帐号已经存在，则不能新建用户，否则创建用户信息并存储用户角色关系
            if (userTemp == null) {
                userTemp = new User();
                try {
                    BeanUtil.copyAllProperties(userVo, userTemp);
                } catch (Exception e) {
                    log.error("用户信息转换出错，用户存储失败，用户信息：" + JSONObject.fromObject(userVo));
                    e.printStackTrace();
                    return null;
                }
                userTemp = userRepository.save(userTemp);
                //存储角色资源信息
                if (XaUtil.isNotEmpty(userVo.getUserRoleList())) {
                    ArrayList<UserRole> userRolesList = new ArrayList<>();
                    for (String roleId : userVo.getUserRoleList()) {
                        UserRole userRole = new UserRole();
                        userRole.setModifyId(userVo.getModifyId());
                        userRole.setCreaterId(userVo.getCreaterId());
                        userRole.setRoleId(roleId);
                        userRole.setUserId(userTemp.getId());
                        userRolesList.add(userRole);
                    }
                    userRoleRepository.save(userRolesList);
                }
                return userTemp;
            } else {
                log.error("创建用户失败，用户帐号【" + userTemp.getAccount() + "】已存在");
                return null;
            }
        } else {
            log.error("创建角色失败，传入的用户信息为null");
            return null;
        }
    }

    /**
     * 根据id获取用户详情
     *
     * @param userId 当前用户id
     * @return UserVo
     */
    @Override
    public UserVo findById(String userId) {
        UserVo userVo = new UserVo();
        if (XaUtil.isEmpty(userId)) {
            return null;
        }
        User user = userRepository.findOne(userId);
        if (user == null || XaUtil.isEmpty(user.getId())) {
            log.warn("查询的用户不存在");
            return null;
        }
        //如果查询到用户的基本信息，再封装用户的其它信息到VO对象中
        try {
            BeanUtil.copyAllProperties(user, userVo);
        } catch (Exception e) {
            log.error("复制用户信息失败，用户帐号：" + user.getAccount());
            e.printStackTrace();
            return null;
        }
        //将用户密码设置为空字符串
        userVo.setPassWord("");
        //获取所有角色集合
        Iterable<Role> allRoles = roleRepository.findByDataFlagAndRoleFlag(Constants.DATA_FLAG_OK,
                Constants.ROLE_FLAG_USERED);
        List<Role> allRoleList = new ArrayList<>();
        if (allRoles != null) {
            for (Role allRole : allRoles) {
                allRoleList.add(allRole);
            }
        }
        userVo.setAllRoleList(allRoleList);
        //获取用户所属角色集合
        Iterable<Role> userRoles = roleRepository.findUserByRoleId(userId,
                Constants.DATA_FLAG_OK,
                Constants.DATA_FLAG_OK,
                Constants.ROLE_FLAG_USERED);
        List<String> userRoleList = new ArrayList<>();
        if (userRoles != null) {
            for (Role userRole : userRoles) {
                userRoleList.add(userRole.getId());
            }
        }
        userVo.setUserRoleList(userRoleList);
        //查询用户最近20条日志信息
        List<SearchFilter> filters = new ArrayList<>();
        SearchFilter dataFlagFilter = new SearchFilter("entityId",
                SearchFilter.Operator.EQ, userId);
        filters.add(dataFlagFilter);
        Pageable pageable = WebUitl.buildPageRequest(0, 20, null);//声明分页
        Page<SystemLog> userLogPage = systemLogRepository.findAll(
                DynamicSpecifications.bySearchFilter(filters, SystemLog.class), pageable);
        if (XaUtil.isNotEmpty(userLogPage)) {
            userVo.setUserLogList(userLogPage.getContent());
        }
        //设置审核人和更新人
        Set<String> ids = new HashSet<>();
        //更新人
        if (XaUtil.isNotEmpty(userVo.getModifyId())) {
            ids.add(userVo.getModifyId());
        }
        //审核人
        if (XaUtil.isNotEmpty(userVo.getAuditId())) {
            ids.add(userVo.getAuditId());
        }
        Iterable<User> allUserAudit = userRepository.findAll(ids);
        Map<String, String> userNameMap = new HashMap<String, String>();
        if (allUserAudit != null) {
            User auditer = null;
            Iterator<User> iterator = allUserAudit.iterator();
            while (iterator.hasNext()) {
                auditer = iterator.next();
                userNameMap.put(auditer.getId(), auditer.getAccount());
            }
            userVo.setModifyUserName(userNameMap.get(userVo.getModifyId()));
            userVo.setAuditUserName(userNameMap.get(userVo.getAuditId()));
        }
        //查询用户部门信息
        String deptId = user.getDeptId();
        Department dept = deptRepostory.findByIdAndDeptFlagAndDataFlag(deptId,
                Constants.DATA_FLAG_OK, Constants.DATA_FLAG_OK);
        if (dept != null && XaUtil.isNotEmpty(dept.getDeptName())) {
            userVo.setDeptId(dept.getId());
            userVo.setUserDeptName(dept.getDeptName());
        }
        return userVo;
    }

    /**
     * 保存用户信息
     *
     * @param user 用户对象
     * @return user 用户对象
     */
    @Override
    public User saveInfo(User user) {
        String id = user.getId();
        User userPo = null;
        if (XaUtil.isNotEmpty(id)) {
            userPo = userRepository.findOne(id);
            if (XaUtil.isNotEmpty(user.getRealName())) {
                userPo.setRealName(user.getRealName());
            }
            if (XaUtil.isNotEmpty(user.getEmailAddress())) {
                userPo.setEmailAddress(user.getEmailAddress());
            }
            if (XaUtil.isNotEmpty(user.getIdCard())) {
                userPo.setIdCard(user.getIdCard());
            }
            if (XaUtil.isNotEmpty(user.getPhoneNum())) {
                userPo.setPhoneNum(user.getPhoneNum());
            }
            if (XaUtil.isNotEmpty(user.getNickname())) {
                userPo.setNickname(user.getNickname());
            }
            userPo.setModifyId(user.getModifyId());
            userPo.setModifyTime(new Date());
            return userRepository.save(userPo);
        } else {
            log.error("修改对象失败，该对象id不存在！");
            return null;
        }
    }

    /**
     * 修改用户密码
     *
     * @param userVo 用户vo
     * @return boolean
     */
    @Override
    public boolean updatePassWord(UserVo userVo) {
        boolean result;
        User user = userRepository.findOne(userVo.getId());
        if (XaUtil.isNotEmpty(user)) {
            if (XaUtil.isNotEmpty(user.getPassWord()) &&
                    user.getPassWord().equals(MD5Util.getMD5String(userVo.getPassWord()))) {
                user.setModifyId(userVo.getModifyId());
                user.setModifyTime(new Date());
                user.setPassWord(MD5Util.getMD5String(userVo.getNewPwd()));
                userRepository.save(user);
                result = true;
            } else {
                log.error("修改密码失败，原密码不正确，用户Account：" + user.getAccount());
                result = false;
            }
        } else {
            log.error("修改密码失败，用户ID：" + userVo.getId());
            result = false;
        }
        return result;
    }
}
